package edu.xhu.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore.LoadStoreParameter;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class ClientActivity extends Activity {
	
	private String URL_S = "http://jwc.xhu.edu.cn";		//连接地址
	private String UserID = "312009080611210";		//帐号
	private String password = "511212303311";	//密码
	private String user_Name;	//姓名

	//location
	protected String locationMessage = null;
	//viewstate---在登录时，传输的信息中要包含viewstate
	protected String viewState = null;
	//网页源代码
	private String source;
	//课程表的源代码
	private String tableSource;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);

        try {
			load();
		} catch (IOException e) {
			Log.e("异常", e.toString());
		}
        
    }
    
    private void load()throws IOException{
    	GetLocation();
    	Login_web(URL_S + locationMessage);
    	CatchUserName();
    	Get_tTable();
    	
    	System.out.println(tableSource);
    }
    
    public void GetLocation()throws IOException{
		URL url = new URL(URL_S);
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();

		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		connection.setInstanceFollowRedirects(false);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.connect();
		//return information
		String message = null;
		//get the information -- location
		message = connection.getHeaderField("Location");
		this.locationMessage = message;
		try {
			//在获取location的同时，并得到viewstate
			getViewState();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
    
  //获取viewstate
  	public void getViewState()throws IOException{
  		URL url = new URL(URL_S);
  		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
  		connection.setDoOutput(true);
  		connection.setRequestMethod("GET");
  		connection.setInstanceFollowRedirects(true);
  		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  		connection.connect();
  		//得到网页源码
  		BufferedReader out = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gb2312"));
  		StringBuffer s_html = new StringBuffer();
  		String line;
  		while((line=out.readLine()) != null){
  			s_html.append(line + "\n");
  		}

  		//获取viewstate----重新获取网页源码，从中截取viewstate
  		source = s_html.toString();
  		source = source.split("_VIEWSTATE")[1];
  		source = source.split("/>")[0];
  		source = source.split("=")[1];
  		source = source.split("\"")[1];
  		source = source.split("\"")[0];
  		viewState = source;

  	}
  	
  //登录，并判断是否登录成功
  	public boolean Login_web(String urlS)throws IOException{
  		URL url = new URL(urlS);
  		HttpURLConnection connection = (HttpURLConnection)url.openConnection();

  		connection.setDoOutput(true);
  		connection.setRequestMethod("POST");
  		connection.setUseCaches(false);
  		connection.setInstanceFollowRedirects(false);
  		//登录时向服务器传输的值：userid，password，身份（默认学生）
  		String Login_IF = "__VIEWSTATE="+viewState+"&TextBox1="
  				+UserID + "&TextBox2="+password+"&RadioButtonList1="+"学生"+"&Button1=&lbLanguage=";
  		OutputStream out = connection.getOutputStream();
  		out.write(Login_IF.getBytes());
  		out.close();
  		connection.connect();
  		String login_TF = null;
  		login_TF = connection.getHeaderField("Location");
  		locationMessage = login_TF;
  		//登录成功返回true，失败返回false
  		if(login_TF == null || login_TF.equals(""))
  			return false;
  		else
  			return true;
  	}

  //获取课表的源代码
  	public void Get_tTable()throws IOException{
  		URL url = new URL(TTableURL());
  		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
  		connection.setDoOutput(true);
  		connection.setRequestMethod("GET");
  		connection.setInstanceFollowRedirects(true);
  		connection.setRequestProperty("Referer", URL_S + locationMessage);
  		connection.connect();
  		//获取源代码
  		BufferedReader out = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gb2312"));
  		StringBuffer s_html = new StringBuffer();
  		String line;
  		while((line=out.readLine()) != null){
  			s_html.append(line + "\n");
  		}
  		//返回课表源代码
  		tableSource = s_html.toString();
  	}

  	//从获取的首页源代码中截取用户的姓名
  	public void CatchUserName()throws IOException{

  		URL url = new URL(URL_S + locationMessage);
  		HttpURLConnection connection = (HttpURLConnection)url.openConnection();

  		connection.setDoOutput(true);
  		connection.setRequestMethod("GET");

  		connection.connect();
  		BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gb2312"));
  		StringBuffer s_html = new StringBuffer();
  		String line;
  		while((line=buffer.readLine()) != null){
  			s_html.append(line + "\n");
  		}
  		//s_html---登录后主界面源代码
  		String s_h = s_html.toString();
  		//提取user_name
  		String uN;
  		String uN1 = s_h.split(UserID)[2];
  		uN = uN1.split("同学")[0];
  		user_Name = uN.trim();
  		
  		
  		Log.e("姓名", user_Name);
  	}
  	
  	public String TTableURL(){
		String location =locationMessage.split("xs")[0] + "xskbcx.aspx?xh="
				+UserID+"&xm="+user_Name+"&gnmkdm=N121603";
		return URL_S + location;
	}
}